#include<iostream>
#include<vector>
#include<string>
#include<unistd.h>
#include<pthread.h>
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;//互斥量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//条件变量
void* Mastercore(void* args)
{
    sleep(3);
    std::cout<<"mastcore 开始唤醒..."<<std::endl;
    std::string name = static_cast<char*>(args);
    //唤醒...
    while(true)
    {
        pthread_cond_signal(&cond);//唤醒等待队列中第一个线程
        sleep(1);
    }
    //pthread_cond_broadcast(&cond);//唤醒等待队列中所有线程
    return nullptr;
}
void* Slavercore(void* args)
{
    std::string name = static_cast<char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);//加锁
        pthread_cond_wait(&cond,&gmutex);//// 等待条件变量，线程进入等待队列，解锁，--其他线程入等待队列--信号--》出等待队列加锁，
        std::cout<<name<<"被唤醒..."<<std::endl;
        //TODO
        pthread_mutex_unlock(&gmutex);//解锁
    }
}
void StartMaster(std::vector<pthread_t>* tidptr)
{
    pthread_t tid;
    int n = pthread_create(&tid,nullptr,Mastercore,(void*)"master thread");
    if(n == 0)
    {
        std::cout<<"master thread create success ..."<<std::endl;
    }
    tidptr->emplace_back(tid);
}

void StartSlaver(std::vector<pthread_t>* tidptr,int threadnum)
{
    for(int i = 0;i< threadnum;i++)
    {
        pthread_t tid;
        char* name = new char[64];
        snprintf(name,64,"thread-%d",i+1);
        int n = pthread_create(&tid,nullptr,Slavercore,name);
        if(n == 0)
        {
            std::cout<<name<<" create success ..."<<std::endl;
        }
        tidptr->emplace_back(tid);
    }
}
void WaitThread(const std::vector<pthread_t>& tids)
{
    for(auto tid:tids)
    {
        pthread_join(tid,nullptr);
    }
}
int main()
{
    std::vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids,5);
    WaitThread(tids);
    return 0;
}